package com.jason.apps.dashboard;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.R;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.alert.EmptyAlert;
import com.jason.apps.alert.ErrorAlert;
import com.jason.apps.dashboard.EditProperty.EditOnClickSelectedListener;
import com.jason.apps.fromdashboard.AllProperty.OnClickSelectedListener;
import com.jason.apps.notify.GMailSender;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

@SuppressLint("ParserError")
public class PropertyDetail extends SherlockFragment implements OnItemSelectedListener {
	
	EditOnClickSelectedListener mCallback;
	
	public EditText Pname;
	public EditText price;
	public EditText address;
	public EditText description;
	public EditText ammenitiespath;
	public EditText imagepath;
	public Button browsepicture;
	public Button addproperty;
	public Spinner agentspinner;
	public Spinner Status;
	public Spinner propertytype;
	public Spinner sellingtype;
	public ImageButton map;
	public TextView Emap;
	
	public static final String KEY_FIRSTNAME = "firstName";
	public static final String KEY_LASTNAME = "lastName";
	public static final String KEY_ID = "person_id";
	public static final String KEY_EMAILADDRESS = "emailAddress";
	String agentSpinner;
	List<String> labels = new ArrayList<String>();
	List<Integer> ids = new ArrayList<Integer>();
	List<String> email = new ArrayList<String>();
	
	final static ArrayList<HashMap<String, String>> Names = new ArrayList<HashMap<String, String>>();
	
	HashMap<String, String> personsName;
		
	String host = "property-portal.uphero.com";
	String ftpuser = "a5596663";
	String ftppass = "ranger123";
	String saveLocation = "/public_html";
	String folderLocation = "/image/";
	static int agentId=-1;
	static String agentEmail=null;
	String pname=null;
	int person_id=-1;
	String image=null;
	String longitude;
	String latitude;
	
	static int id;
	
	final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;
	
	FTPClient con = null;
	
	SherlockFragmentActivity fa;
	ConsumeWebService consume=new ConsumeWebService();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }
		
		View view=inflater.inflate(R.layout.editproperty, container, false);
		fa = (SherlockFragmentActivity) super.getActivity();
		
		 Pname=(EditText)view.findViewById(R.id.EPname);
		 price=(EditText)view.findViewById(R.id.Eprice);
		 address=(EditText)view.findViewById(R.id.Eaddress);
		 description=(EditText)view.findViewById(R.id.Edescription);
		 imagepath=(EditText)view.findViewById(R.id.Eimagepath);
		 browsepicture=(Button)view.findViewById(R.id.Ebrowsepicture);
		 addproperty=(Button)view.findViewById(R.id.Editproperty);
		 agentspinner=(Spinner)view.findViewById(R.id.Eagentspinner);
		 propertytype=(Spinner)view.findViewById(R.id.Epropertytype);
		 sellingtype=(Spinner)view.findViewById(R.id.edit_propertyselling);
		 map=(ImageButton)view.findViewById(R.id.Ebrowsemap);	
		 Emap=(TextView)view.findViewById(R.id.Emap);
		 Status=(Spinner)view.findViewById(R.id.stat);
		 agentspinner.setOnItemSelectedListener(this);

		 new setItem().execute();
		
		 addproperty.setOnClickListener(new View.OnClickListener() {
			 
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if((!Pname.getText().toString().trim().equals(""))&&(!price.getText().toString().trim().equals(""))&&(!address.getText().toString().trim().equals(""))){
					new Edit().execute();
				}
				else{
					FragmentManager fm = getActivity().getSupportFragmentManager();
				     EmptyAlert alert = new EmptyAlert();
				     alert.show(fm, "Alert_Dialog");
				     //clearFields();
				}
			}
		});
		
		return view;
    }
	@Override
    public void onStart() {
        super.onStart();
        
        Bundle args = getArguments();
        if (args != null) {
            // Set article based on argument passed in
            updateView(args.getInt(ARG_POSITION));
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
            updateView(mCurrentPosition);
        }
    }
	public void setUrl(String url){
		imagepath.setText(url);
	}

	public void loadSpinner(Spinner agent){

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, labels);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        agent.setAdapter(dataAdapter);
        agent.setOnItemSelectedListener(this);

	}
	public void updateView(int position){
		
		HashMap<String, String> map = EditProperty.mylist.get(position);
    	
		String name=map.get("property_name");
    	String setPrice=map.get("price");
    	String setDescription=map.get("property_description");
    	String add=map.get("address");
    	String type=map.get("type");
    	image=map.get("image");
    	pname=map.get("name");
    	String sell=map.get("selling_type");

    	id=Integer.parseInt(map.get("property_id"));
    	    	
    	int typeposition=-1;
    	
    	if(type.equals("Building")){
    		typeposition=0;
    	}
    	else if(type.equals("House")){
    		typeposition=1;
    	}
    	else if(type.equals("Office")){
    		typeposition=2;
    	}
    	
    	if(sell.equals("For Rent")){
    		sellingtype.setSelection(0);
    	}
    	else
    		sellingtype.setSelection(1);
    	
    	
    	Pname.setText(name);
    	price.setText(setPrice);
    	address.setText(add);
    	description.setText(setDescription);
    	propertytype.setSelection(typeposition);
    	
    	//agentspinner.setSe
    	
    	mCurrentPosition = position;
	}
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }
	public void setLongLat(String lon,String lat){
		
		Emap.setText(lon+"-"+lat);	
		latitude=lat;
		longitude=lon;
	}
	public List<String> getAllLabels(){
	       // List<String> labels = new ArrayList<String>();
	 
	        String data = consume.getAllPerson();
			 
			 try {
				 	labels.add("None");
				 	ids.add(0);
				 	email.add("nothing");
					JSONArray array = new JSONArray(data);
					
					for (int i = 0; i < array.length(); i++) {
						//personsName=new HashMap<String, String>();
						JSONObject e = array.getJSONObject(i);
						labels.add(e.getString(KEY_FIRSTNAME)+" "+e.getString(KEY_LASTNAME));
						ids.add(e.getInt(KEY_ID));
						email.add(e.getString(KEY_EMAILADDRESS));
						//labels.add(personsName);
					}
					
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
				}finally{
					
				}
	        
	        return labels;
	    }
	

	//Asynctask
	public class Edit extends AsyncTask<Void, Void, Void> {

	    private ProgressDialog dialog;
	    boolean results;

	    protected void onPreExecute() {
	    		this.dialog = new ProgressDialog(fa);
	            this.dialog.setMessage("Loading...");
	            this.dialog.show();
	    }


	    protected Void doInBackground(final Void... unused) {
	    	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	 	   //get current date time with Date()
	 	   Date date = new Date();
	 	   String dates=dateFormat.format(date);
	    	
	    	String propertyname=Pname.getText().toString();
	    	String Address=address.getText().toString();
	    	String Pprice=price.getText().toString();
	    	String Pdescription=description.getText().toString();
	    	String Pimagepath=imagepath.getText().toString().trim();
	    	String getPType=propertytype.getSelectedItem().toString();
	    	String stat=Status.getSelectedItem().toString();
	    	String filenamePicture=new File(Pimagepath).getName();
	    	String selltype=sellingtype.getSelectedItem().toString();
	    	
	    	con = new FTPClient();
			try {
				
			     if((agentId!=0)&&(agentEmail!="nothing")&&(stat.equals("Available"))&&(!Pimagepath.equals(""))){
			    	 con.connect(host);
					results = consume.EditProperty(propertyname, Address,
							Pprice, Pdescription, longitude, latitude,
							agentId, getPType, stat, "http://"+host+folderLocation+filenamePicture, id, "1000-10-10",selltype);
					
					

					if (results) {
						
						con.login(ftpuser, ftppass);
						
						con.enterLocalPassiveMode(); // important!
						con.setFileType(FTP.BINARY_FILE_TYPE);
						//property picture
						BufferedInputStream buffIn = null;
						buffIn = new BufferedInputStream(
						new FileInputStream(new File(Pimagepath)));
						
						boolean result1 = con.storeFile(saveLocation
						+ folderLocation + filenamePicture, buffIn);
				
						buffIn.close();
						
						if (result1){
							
						Log.v("upload result", "succeeded");
						con.logout();
						con.disconnect();
						
						try {
							GMailSender sender = new GMailSender(
									"jesonenerez@gmail.com", "jesonenerez");
							sender.sendMail("This is Subject",
									"You are assigned by the St.therese to this property"
											+ Pname.getText().toString(),
									"jesonenerez@gmail.com", agentEmail);
							Log.e("Message", "Na sent bai");
						} catch (Exception e) {
							Log.e("SendMail", e.getMessage(), e);
						}

					}

				} 
			}
			     else if ((stat.equals("Sold")) && (Pimagepath.equals(""))) {

					try {
						results = consume.EditProperty(propertyname, Address,
								Pprice, Pdescription,longitude, latitude,
								agentId, getPType, stat, image, id, dates,selltype);

						if (results) {

							try {
								GMailSender sender = new GMailSender(
										"jesonenerez@gmail.com", "jesonenerez");
								sender.sendMail("This is Subject",
										"You're assigned property has been sold->"
												+ Pname.getText().toString(),
										"jesonenerez@gmail.com", agentEmail);
								Log.e("Message", "Na sent bai");
							} catch (Exception e) {
								Log.e("SendMail", e.getMessage(), e);
							}

						}
					} catch (Exception e) {
						Log.e("", e.getMessage(), e);
					}
				} else if ((stat.equals("Available"))
						&& (Pimagepath.equals(""))) {
					try {
						results = consume.EditProperty(propertyname, Address,
								Pprice, Pdescription, longitude, latitude,
								agentId, getPType, stat, image, id, dates,selltype);

						if (results) {

							try {
								GMailSender sender = new GMailSender(
										"jesonenerez@gmail.com", "jesonenerez");
								sender.sendMail("This is Subject",
										"You're assigned property to this property ->"
												+ Pname.getText().toString(),
										"jesonenerez@gmail.com", agentEmail);
								Log.e("Message", "Na sent bai");
							} catch (Exception e) {
								Log.e("SendMail", e.getMessage(), e);
							}

						}
					} catch (Exception e) {
						Log.e("", e.getMessage(), e);
					}
				}
				

			} catch (Exception e) {
				Log.e("","",e);
			}
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
	    	
	    	if(results){
	    		FragmentManager fm = getActivity().getSupportFragmentManager();
	    		 AlertDialogFragment alert = new AlertDialogFragment();
	    		 alert.show(fm, "Alert_Dialog");
	    		 clearFields();
	    		 fm.popBackStack();
	    		
	    	}
	    	else{
	    		FragmentManager fm = getActivity().getSupportFragmentManager();
			     ErrorAlert alert = new ErrorAlert();
			     alert.show(fm, "Alert_Dialog");
	    	}
	    	
	    	if (this.dialog!=null) {
	            this.dialog.dismiss();
	            }  
	     }
	  }
	//Asynctask
		public class setItem extends AsyncTask<Void, Void, Void> {

			    private final ProgressDialog dialog = new ProgressDialog(fa);

			    protected void onPreExecute() {

			            this.dialog.setMessage("Loading...");
			            this.dialog.show();
			    }

			    protected Void doInBackground(final Void... unused) {
			    	getAllLabels();
			    	
			        return null; 
			    }
			    protected void onPostExecute(Void result) {
			    	
			    	loadSpinner(agentspinner);
			    	
			    	for(int i=0;i<labels.size();i++){
			    		if(pname.equals(labels.get(i))){
			    			agentspinner.setSelection(i);
			    			agentId=ids.get(i);
			    		    agentEmail=email.get(i); 
			    			return;
			    		}
			    	if (this.dialog!=null) {
			            this.dialog.dismiss();
			            }  
			     }
			    }
			  }

	public void onItemSelected(AdapterView<?> parent, View arg1, int position,
			long arg3) {
		
		int posId=parent.getSelectedItemPosition();		
	    agentId=ids.get(position);
	    Log.e("idits", ""+agentId);
	    agentEmail=email.get(position); 
	}
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	public void clearFields(){
		 Pname.setText("");
		 price.setText("");
		 address.setText("");
		 description.setText("");
		 imagepath.setText("");
		 agentspinner.setSelection(0);
		 propertytype.setSelection(0);
		 
	}
	
}



   

